package com.nokia.pc3.core.transformers;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nokia.pc3.core.xform.Base64ende;
import com.nokia.pc3.core.xform.Transformer;

/**
 * Regular expression transformer. Transformer descriptor arg 'args' is a base64
 * encoded regular expression.
 * 
 * @author jcroke
 * 
 */
public class RegEx1Xfm extends Transformer {

	@Override
	public void run() {
		System.out.println("Run: " + this.getClass().getCanonicalName());

		String input = (String) getInput();
		String[] argv = getArgv();
		String regex = Base64ende.decode(argv[0]);

		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(input);
		String[] labels = getLabels();
		int labelsLength = labels.length;

		if (matcher.find()) {
			if (matcher.groupCount() + 1 != labelsLength) {
				System.out.println("Expecting " + labelsLength
						+ " matches, got " + matcher.groupCount());
				return;
			}

			for (int i = 0; i < labelsLength; i++) {
				try {
					/*
					 * Put sub-outputs
					 */
					putOutput(labels[i], matcher.group(i));

				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		}
	}
}
